//
//  LCArchiveManager.m
//  LCAESFileEncryption
//
//  Created by yxl on 2022/4/1.
//

#import "LCArchiveManager.h"
#import "RNEncryptor.h"
#import "RNDecryptor.h"

#define aPassword  @"LCArchiveManagerPassword"

@implementation LCArchiveManager

#pragma  mark --Image加解密
/// 图片加密
+(void)imageEncryptionImageName:(NSString *)imageName Type:(NSString *)type
{
    NSString *filePath = [[NSBundle mainBundle]pathForResource:imageName ofType:type];
    __block NSData *data = [NSData dataWithContentsOfFile:filePath];
    __block NSError *error;
    // 本地存储加密图片路径
    NSString *fileEncryPath = [NSHomeDirectory()stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@",imageName]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断是否已存在加密文件，若存在直接执行解密过程。
    if ([fileManager fileExistsAtPath:fileEncryPath]) {
        return;
    }
    //异步去加密，防止占用太多内存
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //加密
        NSData *encryptedData = [RNEncryptor encryptData:data withSettings:kRNCryptorAES256Settings password:aPassword error:&error ];
        if (!error) {
            NSLog(@"^_^ 图片加密成功 ……——(^_^)\n");
        }
        //在主线程上写入文件
        dispatch_sync(dispatch_get_main_queue(), ^{
            BOOL yes = [encryptedData writeToFile:fileEncryPath atomically:NO];
            if (yes) {
                NSLog(@"加密图片文件写入成功");

            }else{
                NSLog(@"加密图片文件写入失败");
            }
            NSLog(@"图片写入PDF路径：%@",fileEncryPath);
        });
    });
}

/// 图片解密获取
+(UIImage *)imageDecryptionImageFileName:(NSString *)imageFileName{
    NSString *fileDecryPath = [NSHomeDirectory()stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@",imageFileName]];
    NSData *encryptedData = [NSData dataWithContentsOfFile:fileDecryPath];
    NSError *error;
    NSData *decryptedData = [RNDecryptor decryptData:encryptedData
                                        withPassword:aPassword
                                               error:&error];
    if (!error) {
        NSLog(@"^_^ 图片解密成功 ……——(^_^)\n");
        return [UIImage imageWithData:decryptedData];
    }
    return nil;
}


#pragma mark - Plist文件加解密
/// Plist文件加密
+(void)plistEncryptionPlistName:(NSString *)plistName Type:(NSString *)type{
    __block NSData *encryptedData;
    __block NSError *error;
    // 本地存储加密图片路径
    NSString *fileEncryPath = [NSHomeDirectory()stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@",plistName]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断是否已存在加密文件，若存在直接执行解密过程。
    if ([fileManager fileExistsAtPath:fileEncryPath]) {
        return;
    }
    NSURL *URL=[[NSBundle mainBundle] URLForResource:plistName withExtension:type];
    //plist 文件为字典类型
    NSDictionary *dic=[NSDictionary dictionaryWithContentsOfURL:URL];
    NSError *parseError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    //异步去加密，防止占用太多内存
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //加密
        encryptedData = [RNEncryptor encryptData:jsonData withSettings:kRNCryptorAES256Settings password:aPassword error:&error ];
        if (!error) {
            NSLog(@"^_^ plist文件加密成功 ……——(^_^)\n");
        }
        //在主线程上写入文件
        dispatch_sync(dispatch_get_main_queue(), ^{
            BOOL yes = [encryptedData writeToFile:fileEncryPath atomically:NO];
            if (yes) {
                NSLog(@"加密plist文件写入成功");

            }else{
                NSLog(@"加密plist文件写入失败");
            }
            NSLog(@"写入plist路径：%@",fileEncryPath);
        });
    });
}

/// Plist解密获取
+(NSDictionary *)plistDecryptionPlistFileName:(NSString *)plistFileName{
    NSString *fileDecryPath = [NSHomeDirectory()stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@",plistFileName]];
    NSData *encryptedData = [NSData dataWithContentsOfFile:fileDecryPath];
    //    解密
    NSError *error;
    NSData *decryptedData = [RNDecryptor decryptData:encryptedData
                                        withPassword:aPassword
                                               error:&error];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:decryptedData options:NSJSONReadingMutableContainers error:&error];
    if (error) {
      //解析出错
        NSLog(@"error===%@",error);
    }
    return dic;
}

#pragma mark - 清除
+(void)clearArchiverData
{
    NSError *error;
    NSString *fileEncryPath = [NSHomeDirectory()stringByAppendingPathComponent:@"/Documents"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager removeItemAtPath:fileEncryPath error:&error]){
        NSLog(@"清除本地序列化的文件成功....:%@",error);
    } else {
        NSLog(@"清除本地序列化的文件失败....:%@",error);
    }
}

@end
